﻿using Consul;

namespace S.Produce.Read.Api.Common
{
    /// <summary>
    /// Consul辅助类
    /// </summary>
    public static class ConsulHelper
    {
        /// <summary>
        /// 服务注册
        /// </summary>
        /// <param name="app"></param>
        /// <param name="conf">配置</param>
        /// <param name="lifetime">应用的生命周期></param>
        /// <returns></returns>
        public static IApplicationBuilder AddConsul(this IApplicationBuilder app, IConfiguration conf, IHostApplicationLifetime lifetime)
        {
            //1、consul客户端
            ConsulClient consulClient = new ConsulClient(x =>
            {
                x.Address = new Uri("http://10.31.56.24:8500/");//服务注册中心地址
                x.Datacenter = "dc1";//数据中心
            });
            //2、服务信息
            string serviceIP = conf["ServiceIP"];
            int port = int.Parse(conf["port"]);
            //3、注册服务
            //(1)组装服务注册信息
            var reg = new AgentServiceRegistration()
            {
                ID = DateTime.Now.ToString("yyyyMMddHHmmss"),//服务id，唯一
                Name = "ConsulTest",//服务名称
                Address = serviceIP,
                Port = port,
            };
            //(2)服务注册
            consulClient.Agent.ServiceRegister(reg).Wait();

            //4、应用程序终止，取消注册
            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(reg.ID).Wait();
            });
            return app;
        }
    }
}
